package com.dk.service.cart;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.dk.pojo.item.TbItem;
import com.dk.pojo.order.Cart;
import com.dk.pojo.order.TbOrderItem;
import com.dk.redis.CartRedis;
import com.dk.service.item.ItemService;
import com.dk.service.seller.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Component
public class CartServiceImpl implements CartService {
    @Reference
    private ItemService itemService;
    @Reference
    private SellerService sellerService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<Cart> setCart(List<Cart> cartList, Long itemId, Integer num) {
        //1.根据商品SKU ID查询SKU商品信息
        TbItem item = itemService.getItemById(itemId);
        if (item == null) {
            throw new RuntimeException("商品不存在");
        }
        //2.获取商家ID
        String sellerId = item.getSellerId();
        //3.根据商家ID判断购物车列表中是否存在该商家的购物车
        Cart cart = searchCartBySellerId(cartList, sellerId);
        //4.如果购物车列表中不存在该商家的购物车
        if (cart == null) {
            //4.1 新建购物车对象
            cart = new Cart();
            cart.setSellerName(item.getSeller());
            cart.setSellerId(item.getSellerId());
            //4.2 将新建的购物车对象添加到购物车列表
            TbOrderItem orderItem = createOrderItem(item,num);
            List<TbOrderItem> orderItemList = new ArrayList<>();
            orderItemList.add(orderItem);
            cart.setOrderItemList(orderItemList);
            cartList.add(cart);
        } else {
            //5.如果购物车列表中存在该商家的购物车
            // 查询购物车明细列表中是否存在该商品
            TbOrderItem orderItem = searchOrderItmeByItemId(cart.getOrderItemList(),itemId);

            if (orderItem == null) {
                //5.1. 如果没有，新增购物车明细
                orderItem = createOrderItem(item,num);
                cart.getOrderItemList().add(orderItem);
            } else {
                //5.2. 如果有，在原购物车明细上添加数量，更改金额
                orderItem.setNum(orderItem.getNum() + num);
                orderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue() * orderItem.getNum()));
                // 移除
                if (orderItem.getNum() <= 0) {
                    cart.getOrderItemList().remove(orderItem);
                }
                if (cart.getOrderItemList().size() <= 0) {
                    cartList.remove(cart);
                }
            }

        }

        return cartList;
    }

    private TbOrderItem searchOrderItmeByItemId(List<TbOrderItem> orderItemList, Long itemId) {
        for (TbOrderItem orderItem : orderItemList) {
            if (Objects.equals(orderItem.getItemId(),itemId)) {
                return orderItem;
            }
        }
        return null;
    }

    private TbOrderItem createOrderItem(TbItem item, Integer num) {
        if (num <= 0) {
            throw new RuntimeException("数量非法");
        }
        TbOrderItem orderItem = new TbOrderItem();
        orderItem.setPicPath(item.getImage());
        orderItem.setTitle(item.getTitle());
        orderItem.setItemId(item.getId());
        orderItem.setNum(num);
        orderItem.setPrice(item.getPrice());
        orderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue() * num));
        orderItem.setSellerId(item.getSellerId());
        orderItem.setGoodsId(item.getGoodsId());
        return orderItem;
    }

    private Cart searchCartBySellerId(List<Cart> cartList,String sellerId) {
        for (Cart cart : cartList) {
            if (Objects.equals(cart.getSellerId(),sellerId)) {
                return cart;
            }
        }
        return null;
    }

    @Override
    public void saveCartListByRedis(String username, List<Cart> list) {
        redisTemplate.boundHashOps(CartRedis.CART_LIST).put(username,list);
    }

    @Override
    public List<Cart> getCartFromRedis(String username) {
        List<Cart> cartList = (List<Cart>) redisTemplate.opsForHash().get(CartRedis.CART_LIST, username);
        if (cartList == null) {
            cartList = new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public List<Cart> meangeCartListCookieAndRedis(List<Cart> cookieList, List<Cart> redisList) {
        for (Cart cart : cookieList) {
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            for (TbOrderItem orderItem : orderItemList) {
                redisList = setCart(redisList,orderItem.getItemId(),orderItem.getNum());
            }
        }
        return redisList;
    }
}
